<?php

require_once 'FForm.class.php';

class FEditForm extends FForm
{
    const FUNCTION_INSERT = 'insert';
    const FUNCTION_UPDATE = 'update';
    const FUNCTION_VIEW = 'view';
    
    private $action;
    
    private $dataId;
    
    private $idName;
    
    private $generateIdxField = true;
    
    // Variável que define se o campo identificador deve ser escondido ou não. $generateIdxField deve ser true.
    private $hideIdxField = false;
    
    public function __construct($name = 'feditform')
    {
        if ( $name == 'feditform' )
        {
            $name .= '_' . rand();
        }
        
        $this->setAction(FEditForm::FUNCTION_INSERT);
        
        parent::__construct($name);
    }
    
    public function createTableFields()
    {
        $this->height = 100;
        $this->width = 500;
        
        $controller = $this->controller;
        $controller instanceof FController;
                
        $primaryKeys = $controller->obterChavesPrimariasDaTabela();
        
        // Tratar chaves primárias.
        $pks = array();
        foreach ( $primaryKeys as $pk )
        {
            $pks[] = $pk['name'];
            
            $info = $controller->obterInformacaoDaColuna($pk['name']);
            
            if ( $this->getGenerateIdxField() && !$info->isAutoIncrement() )
            {
                $this->autoAddField($info, true);
            }
        }
        // Fim do bloco de chaves primárias.
                
        // Tratar os outros campos da tabela.
        $fields = $controller->listarColunasDaTabela();
        
        foreach( $fields as $field )
        {
            $info = $controller->obterInformacaoDaColuna($field);
            
            if ( !in_array($info->getName(), $pks) && !$info->isAutoIncrement() )
            {
                $this->autoAddField($info);
            }
        }
        
        $numFields = count($fields);
        if ( $numFields <= 3 )
        {
            $this->height += 40;
        }
        elseif ( $numFields > 10 )
        {
            $this->height -= 120;
            
            if ( $numFields > 15 )
            {
                $this->height -= 100;
            }
            
            if ( $numFields > 20 )
            {
                $this->height -= 150;
            }
            
            if ( $numFields > 25 )
            {
                $this->height -= 200;
            }
        }
    }
    
    private function autoAddField(FColumnInfo $info, $primaryKey = false, $fieldType = NULL)
    {
        $controller = $this->controller;
        $controller instanceof FController;

        $field = NULL;
        
        if ( $fieldType != NULL )
        {
            
        }
        else
        {
            $fieldText = $info->getComment() ? $info->getComment() : ucwords($info->getName());
            
            if ( $foreignKey = $controller->getForeignKey($info->getName()) )
            {
                $foreignController = new FDefaultController();
                $foreignController->setTable($foreignKey['table_ref']);
                
                // Se o número de registros na tabela for maior que o parâmetro, utiliza lookup.
                if ( $foreignController->getCount() <= MAX_REGISTROS_SELECAO )
                {
                    $field = new FSelection($info->getName(), $fieldText, $foreignKey['attribute_ref'], $foreignController->getDescriptionColumn());
                    $field->setTable($foreignKey['table_ref']);
                }
                else
                {
                    $field = new FLookup($info->getName(), $fieldText, $foreignKey['attribute_ref'], $foreignController->getDescriptionColumn());
                    $field->setTable($foreignKey['table_ref']);
                }
                
                $this->height += 45;
            }
            else
            {
                if ( $info->getType() == FController::TYPE_VARCHAR || $info->getType() == FController::TYPE_CHAR || $info->getType() == FController::TYPE_BPCHAR )
                {                    
                    $fieldWidth = $info->getLength() + 50;
                    
                    if ( $fieldWidth >= 150 )
                    {
                        $this->width += 50;
                        
                        if ( $fieldWidth >= 200 )
                        {
                            $this->width += 30;
                        }
                        
                        if ( $fieldWidth >= 250 )
                        {
                            $this->width += 30;
                        }
                        
                        if ( $fieldWidth >= 300 )
                        {
                            $this->width += 50;
                            $this->height += 30;
                        }
                    }
                    
                    // Se no campo couber mais que 256 caracteres, adiciona um text area.
                    if ( $info->getLength() > 256 )
                    {
                        $field = new FTextArea($info->getName(), $fieldText, $fieldWidth);
                        $this->height += 100;
                    }
                    // se não, adiciona um campo texto.
                    else
                    {
                        $field = new FTextField($info->getName(), $fieldText, $fieldWidth);
                        $this->height += 45;
                    }
                    
                    if ( $info->getLength() > 0 )
                    {
                        $field->setMaxLength($info->getLength());
                    }
                }
                elseif ( $info->getType() == FController::TYPE_TEXT )
                {
                    $field = new FTextArea($info->getName(), $fieldText);
                    $this->height += 100;
                }
                elseif ( $info->getType() == FController::TYPE_DATE )
                {
                    $field = new FDateField($info->getName(), $fieldText);
                    $field->setWidth(200);
                    $this->height += 45;
                }
                elseif ( $info->getType() == FController::TYPE_INT || $info->getType() == FController::TYPE_BIGINT )
                {
                    $field = new FNumberField($info->getName(), $fieldText);
                    $field->setWidth(180);
                    $this->height += 45;
                }
                else
                {
                    $field = new FTextField($info->getName(), $fieldText);
                    $this->height += 45;
                }
            }
            
            // Aplica as validações no campo.
            if ( $field instanceof FWidget )
            {
                if ( $primaryKey )
                {
                    if ( $this->getHideIdxField() && $this->getAction() != FEditForm::FUNCTION_UPDATE )
                    {
                        $field->setHidden(true);
                    }

                    $field->setRequired(true);
                                        
                    if ( $this->getAction() == FEditForm::FUNCTION_UPDATE )
                    {
                        $field->setReadOnly(true);
                    }
                    else
                    {                        
                        $field->setValue($info->getDefaultValue());
                    }
                }
                else
                {
                    $field->setRequired($info->getNotNull());

                    if ( $this->getAction() != FEditForm::FUNCTION_UPDATE )
                    {
                        $field->setValue($info->getDefaultValue());
                    }
                }
            }
        }
        
        $this->addFormField($field);
    }
    
    public function generate($show = false)
    {
        if ( !$this->controller instanceof FController )
        {
            $controller = $this->instantiateController();                                    
        }
        else
        {
            $controller = $this->controller;
        }
        
        $controller instanceof FController;
        
        // Tabela
        if ( !$this->tableName )
        {
            $this->tableName = $controller->getTable();
        }
        
        if ( !$this->idName )
        {
            $idx = $controller->obterChavesPrimariasDaTabela($this->tableName);
            $this->idName = $idx[0]['name'];
        }
        
        if ( !$this->action )
        {
            $this->action = self::FUNCTION_INSERT;
        }
        
        // Campos
        foreach( $this->formFields as $key => $field )
        {
            if ( $field instanceof FWidget )
            {
                $field->setFormAction($this->action);
                $fields[] = $field->generate();
            }
        }
        
        if ( !$this->formFields )
        {
            $tableFields = $controller->listarColunasDaTabela($this->tableName);
            foreach( $tableFields as $tableField )
            {
                if ( $tableField != $this->idName )
                {
                    $field = new FTextField($tableField, ucfirst($tableField), 40);
                    $field->setFormAction($this->action);
                    $fields[] = $field->generate();
                }
            }
        }
        
        $fields = implode(',', $fields);
        
        // Bottom Bar
        $bbar = $this->showBottomBar ? 'true' : 'false';
        
        // Maximized
        $maximized = $this->maximized ? 'true' : 'false';        
        
        echo
        "
            Ext.define('{$this->name}', {
                extend: 'FEditForm',
                    title: '{$this->title}',
                    info: '{$this->info}',
                    formFields: [$fields],
                    showBBar: $bbar,
                    maximized: $maximized,
                    width: {$this->width},
                    height: {$this->height},
                    className: '{$controller->getModel()}',
                    table: '{$this->tableName}',
                    idxName: '$idxName'
            });
        ";
        
        if ( $show )
        {
            echo $this->show();
        }
    }
    
    public function getAction() {
        return $this->action;
    }

    public function setAction($action) {
        $this->action = $action;
    }

    public function getDataId() {
        return $this->dataId;
    }

    public function setDataId($dataId) {
        $this->dataId = $dataId;
    }
    
    public function getIdName() {
        return $this->idName;
    }

    public function setIdName($idName) {
        $this->idName = $idName;
    }
    
    public function getGenerateIdxField() {
        return $this->generateIdxField;
    }

    public function setGenerateIdxField($generateIdxField) {
        $this->generateIdxField = $generateIdxField;
    }

    public function getHideIdxField() {
        return $this->hideIdxField;
    }

    public function setHideIdxField($hideIdxField) {
        $this->hideIdxField = $hideIdxField;
    }

}

?>
